﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.Web.Routing;
using System.Security.Cryptography;

using ERPStore.Extensions;
using ERPStore.Web.Html;
using ERPStore.Web.Extensions;

namespace ERPStore.Web.Controllers
{
	/// <summary>
	/// Controlleur des pages "statiques"
	/// </summary>
	// [HandleError(View = "500")]
	public class HomeController : StoreController
	{
		public HomeController(ERPStore.Services.IEmailerService emailerService
			, Services.IEmailTemplateService emailTemplateService
			, ERPStore.Services.IAccountService accountService
			, EventBrokR.IPublisher eventPublisher
			, ERPStore.Services.ICRMService crmService
			, Services.IRewriterService rewriterSerivce)
		{
			this.EmailerService = emailerService;
			this.AccountService = accountService;
			this.EventPublisher = eventPublisher;
			this.EmailTemplateService = emailTemplateService;
			this.CRMService = crmService;
			this.RewriterService = rewriterSerivce;
		}

		protected ERPStore.Services.IEmailerService EmailerService { get; set; }
		protected ERPStore.Services.IAccountService AccountService { get; private set; }
		protected EventBrokR.IPublisher EventPublisher { get; private set; }
		protected Services.IEmailTemplateService EmailTemplateService { get; private set; }
		protected ERPStore.Services.ICRMService CRMService { get; private set; }
		protected Services.IRewriterService RewriterService { get; private set; }

		/// <summary>
		/// Page d'accueil par defaut
		/// </summary>
		/// <returns></returns>
		[ActionFilters.TrackerActionFilter]
		public ActionResult Index()
		{
			ViewData.Model = ERPStore.GlobalConfiguration.Configuration.Settings;
			return View("Index");
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult CatchAll()
		{
			ViewData.Model = ERPStore.GlobalConfiguration.Configuration.Settings;
			if (Request.RawUrl == null 
				|| Request.RawUrl.ToLower().IndexOf("default.aspx") != -1
				|| Request.RawUrl == "/"
				|| Request.RawUrl.IndexOf("/?") != -1
				)
			{
				return View("Index");	
			}

			var viewName = Request.RawUrl;
			if (viewName.IndexOf("?") != -1)
			{
				viewName = viewName.Split('?')[0];
			}
			var ext = ".cshtml";
			var isStatic = false;
			while (true)
			{
				var fileName = Server.MapPath(string.Format("~/views/static/{0}{1}", viewName, ext));
				if (!System.IO.File.Exists(fileName))
				{
					if (ext == ".aspx")
					{
						break;
					}
					ext = ".aspx";
				}
				else
				{
					isStatic = true;
					viewName = viewName + ext;
					break;
				}
			}

			if (isStatic)
			{
				return View(string.Format("~/views/static/{0}", viewName));
			}

			return RewriterService.RewriteUrl(Request);
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult TermsAndConditions()
		{
			ViewData.Model = ERPStore.GlobalConfiguration.Configuration.Settings;
			return View();
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult LegalInformation()
		{
			ViewData.Model = ERPStore.GlobalConfiguration.Configuration.Settings;
			return View();
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult Help()
		{
			ViewData.Model = ERPStore.GlobalConfiguration.Configuration.Settings;
			return View();
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult About()
		{
			ViewData.Model = ERPStore.GlobalConfiguration.Configuration.Settings;
			return View();
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult Error()
		{
			Response.StatusCode = 500;
			return View("500");
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult Contact()
		{
			var contactInfo = new ERPStore.Models.ContactInfo();
			ViewData.Model = contactInfo;
			if (User.Identity.IsAuthenticated)
			{
				var user = User.CurrentUser;
				contactInfo.Email = user.Email;
				contactInfo.FullName = user.FullName;
				contactInfo.PhoneNumber = user.PhoneNumber;
				if (user.Corporate != null)
				{
					contactInfo.CorporateName = user.Corporate.Name;
				}
				contactInfo.UserId = User.CurrentUser.Id;
			}
			return View();
		}

        [AcceptVerbs(HttpVerbs.Post)]
		public ActionResult AjaxContact(ERPStore.Models.ContactInfo contactInfo)
        {
            if (contactInfo == null)
            {
                return PartialView("_ContactForm");
            }
            if (ModelState.IsValid)
            {
                // Envoyer le mail de contact
				contactInfo.IP = Request.UserHostAddress;
				contactInfo.UserAgent = Request.UserAgent;
				bool isNew = false;
				contactInfo.VisitorId = HttpContext.GetOrCreateVisitorId(out isNew);
				try
                {
					CRMService.AddMessageFromContact(contactInfo);
					var emailView = EmailTemplateService.CreateEmailView(ERPStore.GlobalConfiguration.Configuration.Settings.Emailer.ContactRequestView, contactInfo);
					var emailMessage = EmailTemplateService.CreateEmailMessage(emailView);
                    EmailerService.Send(emailMessage);
                }
                catch (Exception ex)
                {
                    LogError(Logger, ex);
                }
            }
            else
            {
                return PartialView("_ContactForm");
            }
            ViewData.Model = contactInfo;
            return PartialView("_ContactMessageSent");
        }


		[AcceptVerbs(HttpVerbs.Post)]
		[System.Web.Mvc.ValidateAntiForgeryToken]
		[ActionFilters.TrackerActionFilter]
		public ActionResult Contact(ERPStore.Models.ContactInfo contactInfo)
		{
			if (contactInfo == null)
			{
				return RedirectToERPStoreRoute(ERPStore.Web.Routing.ERPStoreRoutes.HOME);
			}
			if (ModelState.IsValid)
			{
				// Envoyer le mail de contact
				try
				{
					CRMService.AddMessageFromContact(contactInfo);
					var emailView = EmailTemplateService.CreateEmailView(ERPStore.GlobalConfiguration.Configuration.Settings.Emailer.ContactRequestView, contactInfo);
					var emailMessage = EmailTemplateService.CreateEmailMessage(emailView);
					EmailerService.Send(emailMessage);

					ViewData["IsSent"] = true;
				}
				catch (Exception ex)
				{
					LogError(Logger, ex);
				}
			}
			ViewData.Model = contactInfo;
			return View();
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult StaticPage(string viewName)
		{
			var fileName = Server.MapPath(string.Format("~/views/static/{0}.aspx", viewName));
			if (!System.IO.File.Exists(fileName))
			{
				viewName = viewName + ".cshtml";
			}
			else
			{
				viewName = viewName + ".aspx";
			}

			return View(string.Format("~/views/static/{0}", viewName));
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult HtmlStaticPage(string viewName)
		{
			var fileName = HttpContext.Server.MapPath(string.Format("/views/{0}", viewName));
			return File(fileName, "text/html");
		}


		#region Partial Rendering

		[OutputCache(Duration = 3600)]
		public ActionResult ShowPartial(string key)
		{
			var cryptoService = GlobalConfiguration.Configuration.DependencyResolver.GetService<ERPStore.Services.CryptoService>();
			var viewKey = new
			{
				viewName = string.Empty,
				Salt = DateTime.Now,
			};
			ActionResult result = null;
			try
			{
				var cr = cryptoService.Decrypt(key, viewKey);
				var viewName = Convert.ToString(cr[0]);
				result = new PartialViewResult()
				{
					ViewName = viewName
				};
			}
			catch(Exception ex)
			{
				Logger.Error(ex);
				result = new EmptyResult();
			}

			return result; 
		}

		#endregion
	}
}
